<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;
use think\exception\PDOException;
use Exception;
use think\Db;

/**
 * 入库管理
 *
 * @icon fa fa-circle-o
 */
class Storage extends Backend
{

    /**
     * Storage模型对象
     * @var \app\common\model\Depot\Storage
     */
    protected $model = null;

    /**
     * 是否是关联查询
    */
    protected $relationSearch = true;

    /**
     * 快速搜索
    */
    protected $searchFields = ['id','code'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Depot\Storage;

        $this->SupplierModel = model('Depot.Supplier');

        $this->ProductModel = model('Product.Product');

        $this->DepotProductModel = model('Depot.Product');

        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查询列表数据
    */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->with(['supplier'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 商品入库
    */
    public function add()
    {

        if($this->request->isPost())
        {
            $params = $this->request->param('row/a');

            // 接收添加的商品数据，json字符串转成数组
            $productList = json_decode($params['product'],true);

            // 开启事务
            $this->model->startTrans();
            $this->DepotProductModel->startTrans();

            // 封装入库数据
            $StorageData =[
                'code' => build_code('SU'), // 订单前缀可以自定义
                'supplierid' => $params['supplierid'],
                'type' => $params['type'],
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'status' => 0
            ];

            $StorageStatus = $this->model->validate('common/Depot/Storage')->save($StorageData);

            if($StorageStatus === FALSE)
            {
                $this->error($this->model->getError());
                exit;
            }

            // 处理入库商品数据

            // 存放封装好的商品数据
            $ProductData = [];

            foreach($productList as $item)
            {
                $ProductData[] = [
                    'storageid' => $this->model->id,
                    'proid' => $item['id'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total'],
                ];
            }

            // 验证数据
            $ProductStatus = $this->DepotProductModel->validate('common/Depot/Product')->saveAll($ProductData);

            if($ProductStatus === FALSE)
            {
                $this->model->rollback();
                $this->error($this->DepotProductModel->getError());
            }

            // 大判断
            if($ProductStatus === FALSE || $StorageStatus === FALSE)
            {
                $this->model->rollback();
                $this->DepotProductModel->rollback();
                $this->error(__('添加失败'));
            }else {
                $this->model->commit();
                $this->DepotProductModel->commit();
                $this->success();
            }
        }

        return $this->view->fetch();
    }

    /**
     * 编辑入库
    */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        $supplier = $this->SupplierModel->with(['provinces','citys','districts'])->where('id',$row['supplierid'])->find();

        $ProductList = $this->DepotProductModel->where('storageid',$row['id'])->select();

        // 找不到数据返回错误信息
        if(!$row)
        {
            $this->error(__('该入库单不存在，请重新选择'));
        }

        if(!$supplier)
        {
            $this->error(__('该供应商不存在，请重新选择'));
        }

        if(!$ProductList)
        {
            $this->error(__('该商品不存在，请重新选择'));
        }

        if($this->request->isPost())
        {
            $params = $this->request->param('row/a');

            // 接收添加的商品数据，json字符串转成数组
            $productList = json_decode($params['product'],true);

            // 开启事务
            $this->model->startTrans();
            $this->DepotProductModel->startTrans();

            // 封装入库数据
            $StorageData =[
                'id' => $row['id'],
                'supplierid' => $params['supplierid'],
                'type' => $params['type'],
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'status' => $row['status'],
            ];

            $StorageStatus = $this->model->validate('common/Depot/Storage.edit')->isUpdate(true)->save($StorageData);

            if($StorageStatus === FALSE)
            {
                $this->error($this->model->getError());
                exit;
            }

            // 存放封装好的商品数据
            $ProductData = [];

            // 封装一个在修改时新增的商品
            $NewProData = [];

            foreach($productList as $item)
            {
                if(isset($item['id']))
                {
                    $ProductData[] = [
                        'id' => $item['id'],
                        'proid' => $item['proid'],
                        'nums' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                    ];
                }else{
                    $NewProData[] = [
                        'storageid' => $row['id'],
                        'proid' => $item['proid'],
                        'nums' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                    ];
                }
            }

            $delproid = json_decode($params['delproid']);

            // 删除不需要的商品
            if(!empty($delproid))
            {
                $DelStatus = $this->DepotProductModel->destroy($delproid);

                if($DelStatus === FALSE)
                {
                    $this->model->rollback();
                    $this->error($this->DepotProductModel->getError());
                }
            }

            $NewProStatus = $this->DepotProductModel->validate('common/Depot/Product')->saveAll($NewProData);

            // 验证数据
            $ProductStatus = $this->DepotProductModel->validate('common/Depot/Product.edit')->isUpdate(true)->saveAll($ProductData);

            if($ProductStatus === FALSE || $NewProStatus === FALSE)
            {
                $this->model->rollback();
                $this->error($this->DepotProductModel->getError());
            }

            // 大判断
            if($ProductStatus === FALSE || $StorageStatus === FALSE || $NewProStatus === FALSE)
            {
                $this->model->rollback();
                $this->DepotProductModel->rollback();
                $this->error(__('修改失败'));
            }else {
                $this->model->commit();
                $this->DepotProductModel->commit();
                $this->success();
            }
        }

        // 商品的数据
        $productData = [];

        foreach($ProductList as $item)
        {
            $product = model('Product.Product')->with(['type','unit'])->find($item['proid']);

            $productData[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];;

        }

        $data = [
            'row' => $row,
            'supplier' => $supplier,
        ];

        $this->assignconfig('Product', ['productData' => $productData]);

        return $this->view->fetch('',$data);
    }

    /**
     * 软删除
    */
    public function del($ids = null)
    {
        if($this->request->isAjax())
        {
            $row = $this->model->where(['id' => ['in',$ids]])->select();

            if(empty($row))
            {
                $this->error(__('请选择需要删除入库单'));
            }

            $result = $this->model->destroy($ids);

            if($result === FALSE)
            {
                $this->error(__('删除入库单失败'));
            }else {
                $this->success();
            }
        }
    }

    /**
     * 回收站
    */
    public function recyclebin()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->onlyTrashed()
                ->with(['supplier'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 还原
    */
    public function restore($ids = null)
    {
        $row = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->select();

        if(!$row)
        {
            $this->error(__('请选择需要还原记录'));
        }

        $result = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->update(['deletetime' => null]);

        if($result != true)
        {
            $this->error(__('还原失败'));
        }else{
            $this->success();
        }
    }

    /**
     * 真实删除
    */
    public function destroy($ids = null)
    {
        if($this->request->isAjax())
        {
            Db::startTrans();

            try {
                $row = $this->model->onlyTrashed()->where(['id' => ['in',$ids]])->select();

                if(empty($row))
                {
                    throw new Exception(__("请选择需要删除入库单"));
                }

                $StorageProduct = $this->DepotProductModel->where(['storageid' => ['in',$ids]])->column('id');

                $StorageStatus = $this->model->destroy($ids,true);

                if($StorageStatus === FALSE)
                {
                    throw new Exception(__($this->model->getError()));
                }

                $ProductStatus = $this->DepotProductModel->destroy($StorageProduct);

                if($ProductStatus === FALSE)
                {
                    throw new Exception(__($this->DepotProductModel->getError()));
                }

                Db::commit();
            } catch (PDOException|Exception $e) {
                Db::rollback();
                $this->error(__($e->getMessage()));
            }

            $this->success();
        }
    }
    

    /**
     * 撤回审核
    */
    public function cancel($ids = null)
    {
        if($this->request->isAjax())
        {
            $row = $this->model->get($ids);

            if(!$row)
            {
                $this->error(__('该入库不存在，请重新选择'));
            }

            $data = [
                'id' => $row['id'],
                'status' => 0,
                'reviewerid' => $this->auth->id
            ];


            $result = $this->model->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error(__('撤销审核失败'));
            }else{
                $this->success(__('撤销审核成功'));
            }
        }
    }

    /**
     * 入库详情
    */
    public function detail($ids = null)
    {

        $row = $this->model->with(['admin','reviewer'])->find($ids);

        $supplier = $this->SupplierModel->with(['provinces','citys','districts'])->where('id',$row['supplierid'])->find();

        $ProductList = $this->DepotProductModel->where('storageid',$row['id'])->select();

        $productData = [];

        foreach($ProductList as $item)
        {
            $product = model('Product.Product')->with(['type','unit'])->find($item['proid']);

            $productData[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];;

        }

        $data = [
            'row' => $row,
            'supplier' => $supplier,
            'productData' => $productData
        ];

        return $this->view->fetch('',$data);
    }

    /**
     * 入库审核
    */
    public function process()
    {
        if($this->request->isAjax())
        {
            $id = $this->request->param('ids');

            $status = $this->request->param('status');

            $data = [];

            if($status == 1)
            {
                $data = [
                    'id' => $id,
                    'status' => 2,
                    'reviewerid' => $this->auth->id
                ];
            }else{
                $data = [
                    'id' => $id,
                    'status' => 1,
                    'reviewerid' => $this->auth->id
                ];
            }

            $result = $this->model->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error();
            }else{
                $this->success();
            }
        }
    }

    /**
     * 确认入库
    */
    public function storage()
    {
        if($this->request->isAjax())
        {
            $id = $this->request->param('ids');

            $ProductList = $this->DepotProductModel->where('storageid',$id)->select();

            // 开启事务
            $this->model->startTrans();
            model('Product.Product')->startTrans();

            // 更新入库表的数据
            $data = [
                'id' => $id,
                'status' => 3,
                'adminid' => $this->auth->id
            ];

            $result = $this->model->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error($this->model->getError());
            }

            // 封装更新库存
            $ProductData = [];

            // 遍历商品
            foreach($ProductList as $item)
            {
                $product = model('Product.Product')->find($item['proid']);

                if($product['id'] == $item['proid'])
                {
                    $ProductData[] = [
                        'id' => $product['id'],
                        'stock' => bcadd($product['stock'],$item['nums'])
                    ];
                }
            }

            $ProductStatus = model('Product.Product')->isUpdate(true)->saveAll($ProductData);

            if($ProductStatus === FALSE)
            {
                $this->model->rollback();
                $this->error(model("Product.Product")->getError());
            }

            if($result === FALSE || $ProductStatus === FALSE)
            {
                $this->model->rollback();
                model("Product.Product")->rollback();
                $this->error();
            }else{
                $this->model->commit();
                model("Product.Product")->commit();
                $this->success();
            }

        }
    }

    /**
     * 查询供应商
    */
    public function supplier()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->SupplierModel
                ->with(['provinces','citys','districts'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 商品
    */
    public function product()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->ProductModel
                ->with(['type','unit'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }
}
